﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CZ.PAEZ.SaleManager.FormPlugIns
{
    [Description("提货联表单获取发票号")]
    [HotUpdate]
    public class PickGoodsForm : AbstractBillPlugIn
    {
        /// <summary>
        /// 当前行号
        /// </summary>
        private int mCurrSeq = -1;

        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            string sql = "";
            string fid = "";
            string FDocumentStatus = this.Model.GetValue("FDocumentStatus")?.ToString();
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "PAEZ_TBGETINVOICE": // PAEZ_tbGetInvoice 获取发票号
                    Act_ABIC_GetInvoice();
                    break;
                case "PAEZ_TBUNCLOSE": // PAEZ_tbUnClose 强反关闭
                    if (FDocumentStatus.Equals("Z"))
                    {
                        this.View.ShowErrMessage("单据保存后才能使用该功能！");
                        return;
                    }
                    fid = this.Model.DataObject["Id"].ToString();
                    sql = $"/*dialect*/update PAEZ_t_Lading set FCLOSESTATUS='A' where FID={fid}";
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                    break;
                case "PAEZ_TBCLOSE": // PAEZ_tbClose 强关闭
                    if (FDocumentStatus.Equals("Z"))
                    {
                        this.View.ShowErrMessage("单据保存后才能使用该功能！");
                        return;
                    }
                    fid = this.Model.DataObject["Id"].ToString();
                    sql = $"/*dialect*/update PAEZ_t_Lading set FCLOSESTATUS='B' where FID={fid}";
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                    break;
                case "PAEZ_TBREPEATINVOICE": // PAEZ_tbRepeatInvoice 勾选发票重开标记
                    if (FDocumentStatus.Equals("Z"))
                    {
                        this.View.ShowErrMessage("单据保存后才能使用该功能！");
                        return;
                    }
                    fid = this.Model.DataObject["Id"].ToString();
                    sql = $"/*dialect*/update PAEZ_t_Lading set FRepeatInvoice=1 where FID={fid}";
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                    break;
                case "PAEZ_TBUNREPEATINVOICE": // PAEZ_tbUnRepeatInvoice 取消发票重开标记
                    if (FDocumentStatus.Equals("Z"))
                    {
                        this.View.ShowErrMessage("单据保存后才能使用该功能！");
                        return;
                    }
                    fid = this.Model.DataObject["Id"].ToString();
                    sql = $"/*dialect*/update PAEZ_t_Lading set FRepeatInvoice=0 where FID={fid}";
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                    break;
            }
        }

        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            // 复制后，清空发票、发票批号
            string FDocumentStatus = this.Model.GetValue("FDocumentStatus").ToString();
            if (FDocumentStatus == "Z")
            {
                this.Model.SetValue("FInvoiceLot", "");
                this.Model.SetValue("FInvoice", "");
                this.Model.SetValue("FRepeatInvoice", 0);

                var count = this.Model.GetEntryRowCount("FEntity");
                for (int i = 0; i < count; i++)
                {
                    this.Model.SetValue("FInvoiceqty", "0", i);
                    this.Model.SetValue("FInvoiceStatus", "0", i);
                }
            }
        }

        public override void EntityRowClick(EntityRowClickEventArgs e)
        {
            base.EntityRowClick(e);
            if(e.Key.EqualsIgnoreCase("FEntity"))
                mCurrSeq = e.Row;
        }

        public override void EntityRowDoubleClick(EntityRowClickEventArgs e)
        {
            base.EntityRowDoubleClick(e);
            if (e.Key.EqualsIgnoreCase("FEntity"))
                mCurrSeq = e.Row;
        }

        public override void AfterEntryBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterEntryBarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "PAEZ_TBWASTEROW": // PAEZ_tbWasteRow 行作废
                    Act_AEBIC_WasteRow();
                    break;
                case "PAEZ_TBUNWASTEROW": // PAEZ_tbUnWasteRow 反作废
                    Act_AEBIC_UnWasteRow();
                    break;
            }
        }

        /// <summary>
        /// 行反作废
        /// </summary>
        private void Act_AEBIC_UnWasteRow()
        {
            string FRepeatInvoice = this.Model.GetValue("FRepeatInvoice").ToString();
            if ("True".Equals(FRepeatInvoice))
            {
                this.View.ShowErrMessage("重开发票单无需反作废！");
                return;
            }
            if (mCurrSeq < 0)
            {
                this.View.ShowErrMessage("请先选择要反作废的行！");
                return;
            }
            string rowWasteFlag = this.Model.GetValue("F_PAEZ_YWZF", mCurrSeq)?.ToString();
            if ("False".Equals(rowWasteFlag))
            {
                this.View.ShowErrMessage("当前行不需要反作废！");
                return;
            }
            int row = mCurrSeq + 1;
            this.View.ShowMessage($"确定要反作废第{mCurrSeq + 1}行吗？", MessageBoxOptions.YesNo, result =>
            {
                if (result == MessageBoxResult.Yes)
                {
                    string fid = this.Model.DataObject["Id"].ToString();
                    string sql = string.Format(@"/*dialect*/
update PAEZ_t_LadingEntry set F_PAEZ_YWZF=0 where FID={0} and FSeq={1};
declare @fid int=0, @feid int=0, @fqty decimal(23, 2)=0
select @fid=oe.FID, @feid=oe.FEntryID, @fqty=le.FQty from T_SAL_ORDERENTRY oe
inner join PAEZ_t_LadingEntry_LK lek on oe.FEntryID=lek.FSId and FSTableName='T_SAL_ORDERENTRY'
inner join PAEZ_t_LadingEntry le on le.FEntryId=lek.FEntryID
where le.FID={0} and le.FSeq={1}
update T_SAL_ORDERENTRY set FMrpCloseStatus='B', F_PAEZ_PickQty=F_PAEZ_PickQty+@fqty
where FEntryId=@feid
if @fid<>0 and ((select count(*) from T_SAL_ORDERENTRY where FID=@fid)=
	(select count(*) from T_SAL_ORDERENTRY where FID=@fid and FMrpCloseStatus='B'))
begin 
    update T_SAL_ORDER set FCloseStatus='B' where FID=@fid
end
", fid, row);
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                }
            });
        }

        /// <summary>
        /// 行作废
        /// </summary>
        private void Act_AEBIC_WasteRow()
        {
            string FRepeatInvoice = this.Model.GetValue("FRepeatInvoice").ToString();
            if ("True".Equals(FRepeatInvoice))
            {
                this.View.ShowErrMessage("重开发票单无需作废！");
                return;
            }
            if (mCurrSeq < 0)
            {
                this.View.ShowErrMessage("请先选择要作废的行！");
                return;
            }
            string rowWasteFlag = this.Model.GetValue("F_PAEZ_YWZF", mCurrSeq)?.ToString();
            if("True".Equals(rowWasteFlag))
            {
                this.View.ShowErrMessage("当前行已经作废！");
                return;
            }
            int row = mCurrSeq + 1;
            this.View.ShowMessage($"确定要作废第{row}行吗？", MessageBoxOptions.YesNo, result =>
            {
                if(result == MessageBoxResult.Yes)
                {
                    string fid = this.Model.DataObject["Id"].ToString();
                    string sql = string.Format(@"/*dialect*/
update PAEZ_t_LadingEntry set F_PAEZ_YWZF=1 where FID={0} and FSeq={1};
declare @fid int=0, @feid int=0, @fqty decimal(23, 2)=0
select @fid=oe.FID, @feid=oe.FEntryID, @fqty=le.FQty from T_SAL_ORDERENTRY oe
inner join PAEZ_t_LadingEntry_LK lek on oe.FEntryID=lek.FSId and FSTableName='T_SAL_ORDERENTRY'
inner join PAEZ_t_LadingEntry le on le.FEntryId=lek.FEntryID
where le.FID={0} and le.FSeq={1}
update T_SAL_ORDER set FCloseStatus='A' where FID=@fid
update T_SAL_ORDERENTRY set FMrpCloseStatus='A', 
    F_PAEZ_PickQty=case when F_PAEZ_PickQty-@fqty>=0 then F_PAEZ_PickQty-@fqty else 0 end
where FEntryId=@feid
", fid, row);
                    DBUtils.Execute(Context, sql);
                    this.View.Refresh();
                }
            });
        }


        private void Act_ABIC_GetInvoice()
        {
            string FDocumentStatus = this.Model.GetValue("FDocumentStatus")?.ToString();
            if (FDocumentStatus.Equals("Z"))
            {
                this.View.ShowErrMessage("单据保存后才能使用该功能！");
                return;
            }
            string FID = this.Model.DataObject["Id"].ToString();
            string FInvoice = this.Model.GetValue("FInvoice")?.ToString();
            GetGoldTaxDiskNo(taxDiskNo =>
            {
                
                if (!FInvoice.IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.ShowWarnningMessage($"已经存在发票号，请勿重复获取！\n");
                    return;
                }

                string sql = string.Format(@"/*dialect*/
select top 1 ip.FID, ip.FNumber, ip.FInvoiceLot from (select * from PAEZ_t_Lading where FID={0}) l
inner join T_BD_CUSTOMER c on c.FCUSTID=l.FCustomerID
inner join PAEZ_BD_InvoicePool ip on ip.FInvoiceType=c.FInvoiceType
where ip.FIsUsed=0 and ip.FTaxDiskNo1={1}
order by Convert(bigint, ip.FNumber) asc
", FID, taxDiskNo);
                var info = DBUtils.ExecuteDynamicObject(Context, sql);
                if (info.Count <= 0)
                {
                    this.View.ShowErrMessage("发票号获取失败，请检查发票池是否存有未使用的发票号！\n");
                    return;
                }
                sql = string.Format(@"/*dialect*/
update l set FInvoice='{2}',FInvoiceLot='{3}',FTaxDiskNo='{4}' from PAEZ_t_Lading l where FID={0};
update ip set FIsUsed=1 from PAEZ_BD_InvoicePool ip where FID={1};",
FID, info[0]["FID"], info[0]["FNumber"], info[0]["FInvoiceLot"], taxDiskNo);
                DBUtils.Execute(Context, sql);

                this.View.ShowMessage("发票号获取成功！");
                this.View.Refresh();
            });
        }


        /// <summary>
        /// 获取金税盘号
        /// </summary>
        /// <param name="callback"></param>
        private void GetGoldTaxDiskNo(Action<string> callback)
        {
            var param = new DynamicFormShowParameter();
            param.FormId = "PAEZ_GoldTaxChoice";
            param.ParentPageId = this.View.PageId;
            param.OpenStyle.ShowType = ShowType.Modal;

            this.View.ShowForm(param, result =>
            {
                if (result.ReturnData.IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.ShowWarnningMessage("未选择有效的金税盘号！");
                    return;
                }
                callback(result.ReturnData.ToString());
            });
        }
    }
}
